<template>
  <div class="userlist-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片组件 -->
    <el-card>
      <!-- 搜索+添加用户 -->
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" :clearable="true" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="1">
          <!-- 添加用户 -->
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" height="250" border stripe style="width: 100%">
        <!-- 添加一个索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="id" label="用户编号"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="email" label="电子邮箱"></el-table-column>
        <el-table-column prop="mg_state" label="用户状态">
          <template slot-scope="scope">
            <!-- scope.row代表的是本行数据对象 -->
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="changeUserstate(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column label="操作" min-width="240px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editUser(scope.row.id,scope.row.email,scope.row.mobile)"></el-button>
            <el-button type="primary" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="编辑用户权限" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-setting" @click="userSetting(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 100]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="total"></el-pagination>
    </el-card>
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" @close="closeDialog">
      <!-- <span>添加用户</span> -->
      <el-form :model="addUserInfo" :rules="addUserRules" ref="addUserRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserInfo.password"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="addUserInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUserInfo">添 加</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="30%" :before-close="editHandleClose" @close="closeEditDialog">
      <el-form :model="editUserInfo" :rules="editUserRules" ref="editUserRef" label-width="80px">
        <el-form-item label="用户ID" prop="username">
          <el-input v-model="editUserInfo.id" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserInfo.mobile"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editUserInfo.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditUser">修 改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      // 自定义表单验证规则
      var checkEmail = (rule, value, callback) => {
        const regEmail = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
        if (regEmail.test(value)) {
          // 合法的邮箱
          return callback()
        }
        callback(new Error('请输入合法的邮箱'))
      }
      var checkMobile = (rule, value, callback) => {
        const regMobile =
          /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
        if (regMobile.test(value)) {
          // 合法的手机号
          return callback()
        }
        callback(new Error('请输入合法的手机号码'))
      }
      return {
        userList: [],
        addUserInfo: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        addUserRules: {
          username: [{
            required: true,
            message: '请输入用户名!',
            trigger: 'blur'
          }, {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }],
          password: [{
              required: true,
              message: '请输入密码!',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 20,
              message: '长度在 6 到 20 个字符',
              trigger: 'blur'
            }
          ],
          email: [{
            required: true,
            message: '邮箱不能为空!',
            trigger: 'blur'
          }, {
            validator: checkEmail,
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: '手机号不能为空!',
            trigger: 'blur'
          }, {
            validator: checkMobile,
            trigger: 'blur'
          }]
        },
        editUserInfo: {
          id: '',
          email: '',
          mobile: ''
        },
        editUserRules: {
          email: [{
            required: true,
            message: '邮箱不能为空!',
            trigger: 'blur'
          }, {
            validator: checkEmail,
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: '手机号不能为空!',
            trigger: 'blur'
          }, {
            validator: checkMobile,
            trigger: 'blur'
          }]
        },
        queryInfo: {
          query: '', // query为搜索的关键字
          pagenum: 1,
          pagesize: 3
        },
        total: 0,
        dialogVisible: false,
        editDialogVisible: false
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      async getUserList() {
        const result = await this.$http.get('/users', {
          params: this.queryInfo
        })
        console.log(result)
        if (!result.data) return this.$message.error(result.meta.msg)
        this.userList = result.data.users
        this.total = result.data.total
        console.log(this.total)
        this.$message.success(result.meta.msg)
      },
      // 监听pagesize改变
      handleSizeChange(newSize) {
        // console.log(newSize)
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      handleCurrentChange(newPage) {
        // console.log(newPage)
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      async changeUserstate(userinfo) {
        // 修改数据的请求,一般都用put方法,模板字符串用反引号
        // console.log(userinfo.mg_state)
        const result = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        if (!result.data) return this.$message.error(result.meta.msg)
        // console.log(result)
        this.$message.success(result.meta.msg)
      },
      addUser() {
        this.dialogVisible = true
      },
      submitUserInfo() {
        //  提交前预验证
        this.$refs.addUserRef.validate(async (valid) => {
          if (valid) return this.$message.error('表单验证失败,请检查')
          const result = await this.$http.post('users', this.addUserInfo)
          if (result.meta.status !== 201) return this.$message.error(result.meta.msg)
          this.$message.success(result.meta.msg)
          this.getUserList()
          this.dialogVisible = false
        })
      },
      editUser(id, email, mobile) {
        this.editUserInfo.id = id
        this.editUserInfo.email = email
        this.editUserInfo.mobile = mobile
        this.editDialogVisible = true
      },
      submitEditUser() {
        // 提交前验证
        this.$refs.editUserRef.validate(async valid => {
          if (!valid) return Error('表单验证失败')
          const result = await this.$http.put(`users/${this.editUserInfo.id}`, this.editUserInfo)
          if (result.meta.status !== 200) return this.$message.error(result.meta.msg)
          this.$message.success(result.meta.msg)
          this.getUserList()
          this.editDialogVisible = false
        })
      },
      // async await 方便解决promise问题
      deleteUser(id) {
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }).then(async () => {
          const result = await this.$http.delete(`users/${id}`)
          if (result.meta.status !== 200) return this.$message.error(result.meta.msg)
          // this.$message.success(result.meta.msg)
          this.getUserList()
          this.$message({
            type: 'success',
            message: result.meta.msg
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      handleClose(done) {
        this.$message.info('放弃添加用户')
        this.dialogVisible = false
      },
      editHandleClose(done) {
        this.$message.info('放弃修改用户')
        this.dialogVisible = false
      },
      // 监听添加用户表单关闭,如果关闭,则清空表单内容
      closeDialog() {
        this.$refs.addUserRef.resetFields()
      },
      closeEditDialog() {
        this.$refs.editUserRef.resetFields()
      }
    }
  }
</script>

<style>
  .userlist-container {
    height: 100%;
  }

  .el-card {
    height: 100%;
  }

  .el-card__body {
    height: 100%;
  }

  .el-table {
    height: 80% !important;
  }
</style>
